// 腾讯云 COS 的使用
const fs = require('fs');
const COS = require('cos-nodejs-sdk-v5');
const cos_config = require('../config').cos_config;
const cos = new COS({
    AppId: cos_config.AppId,
    SecretId: cos_config.SecretId,
    SecretKey: cos_config.SecretKey
})
const tencent_cos = { Bucket: cos_config.Bucket, Region: cos_config.Region }

module.exports.uploadFile = uploadFile;
async function uploadFile(fileArray, dirpath) {
    let dir = 'obj2img/' + dirpath + '/';
    let index = 0;
    //#异步上传
    fileArray.forEach(key => {
        let localFile = './static/img/' + dirpath + '/' + key
        // 腾讯云 文件上传
        let params = {
            Bucket: tencent_cos.Bucket,                         /* 必须 */
            Region: tencent_cos.Region,                         /* 必须 */
            Key: dir + key,                                     /* 存储路径 */
            FilePath: localFile,                                /* 必须 */
        }
        cos.sliceUploadFile(params, function (err, data) {
            if (err) {
                fs.unlinkSync(localFile);
                deleteall('./static/file/' + dirpath)
                deleteall('./static/pdf/' + dirpath)
                deleteall('./static/img/' + dirpath)
                console.log(JSON.stringify({ status: '101', msg: '上传失败', error: JSON.stringify(err) }));
            } else {
                fs.unlinkSync(localFile);
                const imageSrc = 'https://material-1258501264.cos.ap-guangzhou.myqcloud.com/' + data.Key;
                console.log(JSON.stringify({ status: '100', msg: '上传成功', imageUrl: imageSrc }));
                index++;
                if(fileArray.length === index){
                    console.log('= = = = = = = = = = 上传完成 = = = = = = = = =\n' + new Date())
                    deleteall('./static/file/' + dirpath)
                    deleteall('./static/pdf/' + dirpath)
                    deleteall('./static/img/' + dirpath)
                }
            }
        });
    });
    //#返回第一张图片的路径
    return 'https://material-1258501264.cos.ap-guangzhou.myqcloud.com/' + dir + fileArray[0];
}

//#删除文件及其文件夹 
function deleteall(path) {
	let files = [];
	if(fs.existsSync(path)) {
		files = fs.readdirSync(path);
		files.forEach(function(file, index) {
			let curPath = path + "/" + file;
			if(fs.statSync(curPath).isDirectory()) { // recurse
				deleteall(curPath);
			} else { // delete file
				fs.unlinkSync(curPath);
			}
		});
		fs.rmdirSync(path);
	}
};